//
//  SplitPageViewController.m
//  UEAssistant
//
//  Created by mac on 2017/9/8.
//  Copyright © 2017年 youyixinxi. All rights reserved.
//

#import "SplitPageViewController.h"
#import "PPNumberButton.h"
#import "SplitTableViewCell.h"
#import <IQKeyboardManager.h>

#define Screen_width           [UIScreen mainScreen].bounds.size.width
#define Screen_height          [UIScreen mainScreen].bounds.size.height

@interface SplitPageViewController ()<UITableViewDelegate,UITableViewDataSource,PPNumberButtonDelegate,UITextFieldDelegate>{
    
    NSMutableArray                  *_dataSource;
    NSMutableArray                  *_dataSource_sumi;
    NSInteger                       _file_count;
    BOOL                            _ifRestWordIsZero;
    BOOL                            _isVarate;
    NSInteger                       _sumiSplitCount;
}

@property (nonatomic, strong) UITableView            *tableView;
@property (nonatomic, strong) UILabel                *titleName;
@property (nonatomic, strong) UILabel                *totelLabel;
@property (nonatomic, strong) UILabel                *restLabel;
@property (nonatomic, strong) PPNumberButton         *numberButton;
@property (nonatomic, strong) UIButton               *rightButon;
@property (nonatomic, strong) UIButton               *simulateButton;

@end

@implementation SplitPageViewController


- (void)viewWillAppear:(BOOL)animated{
    
    [_rightButon setHidden:NO];
    [IQKeyboardManager sharedManager].enable = YES;

}

- (void)viewWillDisappear:(BOOL)animated{
    
    [_rightButon setHidden:YES];
    [IQKeyboardManager sharedManager].enable = NO;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self initData];
}

- (void)initUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"拆分设置";
    [self.navigationController.navigationBar addSubview:self.rightButon];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.simulateButton];
}


- (void)initData{
    
    _file_count = 2;
    _sumiSplitCount = [self.wordCount integerValue];
    _dataSource_sumi = [NSMutableArray array];
    for (int i = 0; i < _file_count; i ++) {
        [_dataSource_sumi addObject:@"0"];
    }
}


#pragma mark -- Event

//均分预测
- (void)onClickedAveragebtn{
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [self.simulateButton setEnabled:NO];
    //计算每份的字数
    NSMutableArray *countArr = [NSMutableArray array];
    NSInteger count = [self.wordCount integerValue];
    
    for (int i = 0; i < _file_count; i ++) {
        
        if (i == _file_count - 1) {
            [countArr addObject:[NSString stringWithFormat:@"%f",count*1.0/_file_count + count%_file_count]];
        }else{
            [countArr addObject:[NSString stringWithFormat:@"%f",count*1.0/_file_count]];
        }
    }
    NSString *list = [countArr componentsJoinedByString:@","];

    NSDictionary *params = @{@"projectId":detailsModel.product_Id,
                             @"docId":self.doc_id,
                             @"list":list};
    [AvailableNetWorking postWithUrl:fileSplit_varrage_connector params:params successHandler:^(id responseObject) {
        
        NSLog(@"res == %@",responseObject);
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if ([responseObject[@"code"] integerValue] == 200) {
            
            [self.simulateButton setEnabled:YES];
            _dataSource = [NSMutableArray arrayWithArray:responseObject[@"result"]];
            
            if (_dataSource.count < _file_count) {
                [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"选择的份数过多" andTitleColor:[UIColor whiteColor] andCancel:NO];

            }else{
                _ifRestWordIsZero = YES;
                _isVarate = YES;
                [self.tableView reloadData];
                [self.simulateButton setTitle:@"确定拆分" forState:UIControlStateNormal];
            }
            
        }else{
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];

            [self.simulateButton setEnabled:YES];

        }
        
    } falureHandler:^(NSError *error) {
        
        [self.simulateButton setEnabled:YES];

    }];
}


- (void)simulateClickedBtn:(UIButton *)sender{

    if ([sender.titleLabel.text isEqualToString:@"模拟拆分"]) {
        
        [self.simulateButton setEnabled:NO];
        if ([[_restLabel.text substringFromIndex:5] integerValue] > 0) {
            
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"还有部分内容未分配，请完全分配后再拆分" andTitleColor:[UIColor whiteColor] andCancel:NO];
            [self.simulateButton setEnabled:YES];

        }
        else if ([[_restLabel.text substringFromIndex:5] integerValue] < 0){
            
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"分配的字数大于文件总字数，无法拆分" andTitleColor:[UIColor whiteColor] andCancel:NO];
            [self.simulateButton setEnabled:YES];
        }
        else{
            

            NSString *list = [_dataSource_sumi componentsJoinedByString:@","];
            NSDictionary *params = @{@"projectId":detailsModel.product_Id,
                                     @"docId":self.doc_id,
                                     @"list":list};
            [AvailableNetWorking postWithUrl:fileSplit_varrage_connector params:params successHandler:^(id responseObject) {
                
                if ([responseObject[@"code"] integerValue] == 200) {
                    
                    [TopAlertView SetUpbackgroundColor:mainColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"模拟拆分成功，请检查拆分字数是否符合要求" andTitleColor:[UIColor whiteColor] andCancel:NO];
                    [self.simulateButton setEnabled:YES];
                    _dataSource = [NSMutableArray arrayWithArray:responseObject[@"result"]];
                    _ifRestWordIsZero = YES;
                    _isVarate = YES;
                    [self.tableView reloadData];
                    [self.simulateButton setTitle:@"确定拆分" forState:UIControlStateNormal];
                    
                    
                }else{
                    
                    [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];
                    [self.simulateButton setEnabled:YES];

                }
                
            } falureHandler:^(NSError *error) {
                [self.simulateButton setEnabled:YES];

                
            }];
        
        }
    }
    else{
        
        NSDictionary *params = @{@"projectId":detailsModel.product_Id,
                                 @"docId":self.doc_id,
                                 @"docName":self.doc_name,
                                 @"testResult":[self arrayToJSONString:_dataSource]};
        NSLog(@"params ----- %@",params);
        
        [AvailableNetWorking postWithUrl:fileSplit_sure_connector params:params successHandler:^(id responseObject) {
            
            if ([responseObject[@"code"] integerValue] == 200) {
                [[NSNotificationCenter defaultCenter]postNotificationName:@"splitFileRefresh" object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }
        } falureHandler:^(NSError *error) {
            
        }];
        
    }
    
}


- (NSString *)arrayToJSONString:(NSArray *)array
{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

#pragma mark -- <UITableViewDelegate,UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _file_count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_width, 70+15)];
    header.backgroundColor = [UIColor whiteColor];
    
    _titleName = [[UILabel alloc]initWithFrame:CGRectMake(15, 15, 200, 20)];
    _titleName.backgroundColor = [UIColor clearColor];
    _titleName.textColor = [UIColor blackColor];
    _titleName.font = [UIFont systemFontOfSize:16];
    _titleName.text = @"将文件分为";
    [header addSubview:_titleName];
    
    _totelLabel = [[UILabel alloc]initWithFrame:CGRectMake(_titleName.frame.origin.x, _titleName.frame.origin.y+_titleName.frame.size.height, 100, 20)];
    _totelLabel.backgroundColor = [UIColor clearColor];
    _totelLabel.textColor = [UIColor lightGrayColor];
    _totelLabel.font = [UIFont systemFontOfSize:12];
    _totelLabel.text = [NSString stringWithFormat:@"总字数:%@",self.wordCount];
    [header addSubview:_totelLabel];
    
    _restLabel = [[UILabel alloc]initWithFrame:CGRectMake(_totelLabel.frame.origin.x+_totelLabel.frame.size.width, _titleName.frame.origin.y+_titleName.frame.size.height, 120, 20)];
    _restLabel.backgroundColor = [UIColor clearColor];
    _restLabel.textColor = [UIColor lightGrayColor];
    _restLabel.font = [UIFont systemFontOfSize:12];
    if (_ifRestWordIsZero) {
        __block NSInteger totel = 0;
        [_dataSource_sumi enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           
            totel += [obj integerValue];
        }];
        
        _restLabel.text = [NSString stringWithFormat:@"剩余字数:%zd",[self.wordCount integerValue] - totel];
    }else{
        _restLabel.text = [NSString stringWithFormat:@"剩余字数:%@",self.wordCount];
    }
    if (_isVarate) {
        _restLabel.text = @"剩余字数:0";

    }
    [header addSubview:_restLabel];
    

    [header addSubview:self.numberButton];
    
    UILabel *_remark = [[UILabel alloc]initWithFrame:CGRectMake(Screen_Width - 30, 25, 15, 20)];
    _remark.backgroundColor = [UIColor clearColor];
    _remark.textColor = RGB(51, 51, 51, 1);
    _remark.font = [UIFont systemFontOfSize:14];
    _remark.text = @"份";
    [header addSubview:_remark];

    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 65, Screen_Width, 15)];
    view.backgroundColor = RGB(247, 247, 247, 1);
    [header addSubview:view];
    
    return header;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.001f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"fileSplitCell";
    SplitTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell) {
        cell = [[SplitTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.doc_count.delegate = self;
    cell.doc_name.text = [NSString stringWithFormat:@"%@_%zd",self.doc_name,indexPath.row+1];
    
    if (_dataSource.count == 0 && _isVarate) {
        cell.doc_count.text = @"";
    }
    else{
        if (_isVarate) {
            cell.doc_count.text = [NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"wordcount"]];
        }else{
            if ([_dataSource_sumi[indexPath.row] integerValue] == 0) {
                cell.doc_count.text = @"";
            }else{
                cell.doc_count.text = [NSString stringWithFormat:@"%@",_dataSource_sumi[indexPath.row]];
            }
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    UITableViewCell *cell = (UITableViewCell *)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    for (int i = 0; i < _file_count; i ++) {
        if (i == indexPath.row) {
            [_dataSource_sumi replaceObjectAtIndex:i withObject:textField.text];
        }
    }
    _ifRestWordIsZero = YES;
    [self.tableView reloadData];
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}


#pragma mark -- 转json
- (NSString*)dictionaryToJson:(NSDictionary *)dic{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

#pragma mark -- <PPNumberButtonDelegate>

- (void)pp_numberButton:(PPNumberButton *)numberButton number:(NSInteger)number increaseStatus:(BOOL)increaseStatus{

    _file_count = number;
    [_dataSource removeAllObjects];
    [_dataSource_sumi removeAllObjects];
    for (int i = 0; i < _file_count; i ++) {
        [_dataSource_sumi addObject:@"0"];
    }
    _ifRestWordIsZero = NO;
    [self.simulateButton setTitle:@"模拟拆分" forState:UIControlStateNormal];
    [self.tableView reloadData];
}

#pragma mark -- getter
- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Screen_width,Screen_height-50) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = RGB(247, 247, 247, 1);
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.dataSource = self;
        _tableView.delegate = self;

    }
    return _tableView;
}

- (PPNumberButton *)numberButton{

    if (!_numberButton) {
        _numberButton = [PPNumberButton numberButtonWithFrame:CGRectMake(Screen_width - 50 - 70, 22, 80, 26)];
        _numberButton.borderColor = [UIColor colorWithWhite:0.9 alpha:1];
        _numberButton.increaseTitle = @"＋";
        _numberButton.decreaseTitle = @"－";
        _numberButton.currentNumber = 2;
        _numberButton.minValue = 3;
        _numberButton.editing = NO;
        _numberButton.decreaseHide = YES;
        _numberButton.delegate = self;
    }
    return _numberButton;
}

- (UIButton *)rightButon{

    if (!_rightButon) {
        _rightButon = [UIButton buttonWithType:UIButtonTypeSystem];
        _rightButon.backgroundColor = [UIColor clearColor];
        _rightButon.frame = CGRectMake(Screen_Width - 60, 5, 50, 32);
        [_rightButon setTitle:@"均分" forState:UIControlStateNormal];
        [_rightButon setTitleColor:RGB(51, 51, 51, 1) forState:UIControlStateNormal];
        _rightButon.titleLabel.font = [UIFont systemFontOfSize:17];
        [_rightButon addTarget:self action:@selector(onClickedAveragebtn) forControlEvents:UIControlEventTouchUpInside];
        _rightButon.layer.cornerRadius = 16;
        _rightButon.layer.masksToBounds = YES;

    }
    return _rightButon;
}

- (UIButton *)simulateButton{
    
    if (!_simulateButton) {
        _simulateButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _simulateButton.backgroundColor = RGB(51, 187, 238, 1);
        _simulateButton.frame = CGRectMake(0, Screen_Height-110, Screen_Width, 50);
        [_simulateButton setTitle:@"模拟拆分" forState:UIControlStateNormal];
        [_simulateButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _simulateButton.titleLabel.font = [UIFont systemFontOfSize:17];
        [_simulateButton addTarget:self action:@selector(simulateClickedBtn:) forControlEvents:UIControlEventTouchUpInside];
        _simulateButton.layer.masksToBounds = YES;
        
    }
    return _simulateButton;
}


@end
